#include <assert.h>
#include "criticalsection.h"

namespace gecko
{

CriticalSection::CriticalSection(const char* debugName)
{
#if defined(_DEBUG)
	m_DebugName = debugName;
	m_DebugCount = 0;
#else
	// removed unreferenced variable warning
	(void)debugName;
#endif

	InitializeCriticalSection(&m_CriticalSection);
}

CriticalSection::~CriticalSection()
{
#if defined(_DEBUG)
	assert(m_DebugCount == 0);
#endif

	DeleteCriticalSection(&m_CriticalSection);
}

void CriticalSection::Begin()
{
	EnterCriticalSection(&m_CriticalSection);

#if defined(_DEBUG)
	m_DebugCount++;
#endif
}

bool CriticalSection::TryBegin()
{
	bool result = false;
	
	int res = TryEnterCriticalSection(&m_CriticalSection);
	result = (res != 0) ? true : false;

#if defined(_DEBUG)
	if (result)
	{
		m_DebugCount++;
	}
#endif

	return result;
}

void CriticalSection::End()
{
#if defined(_DEBUG)
	{
		m_DebugCount--;
	}
#endif

	LeaveCriticalSection(&m_CriticalSection);
}

}
